package com.office.web;


import com.office.bean.Classes;
import com.office.bean.Major;
import com.office.service.ClassesService;
import com.office.service.MajorService;
import com.office.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ClassesController {

    @Autowired
    ClassesService classesService;

    @Autowired
    MajorService majorService;


    @RequestMapping("/class_list")
    public String class_list(int pageIndex, int pageSize, Model model){
        long count = classesService.findtotalCount();
        Map<String,Object> map = new HashMap<>();
        map.put("pageIndex",(pageIndex-1)*pageSize);
        map.put("pageSize",pageSize);
        List<Classes> classByPage = classesService.findClassByPage(map);
        for (Classes classes : classByPage) {
            long classCount = classesService.findClassCount((int) classes.getId());
            classes.setStudentcount(classCount);
        }
        PageUtils<Classes> pageUtils = new PageUtils<>(pageIndex,pageSize,count,classByPage);
        model.addAttribute("pageUtils",pageUtils);
        return "gradelist";
    }

    @RequestMapping("/delete_class")
    @ResponseBody
    public boolean delete_class(int id){
        return classesService.deleteClass(id);
    }

    @RequestMapping("/class_update/{id}")
    public String  class_update(@PathVariable("id") int id ,Model model){
        Classes classById = classesService.findClassById(id);
        model.addAttribute("class", classById);
        return "gradeupdate";
    }

    @RequestMapping("/classupdate")
    public void classupdate(Classes classes, HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        int update = classesService.update(classes);

        if (update>0){
            response.getWriter().write("<script>alert('更新成功');location.href='/class_list?pageIndex=1&pageSize=5';</script>");
        }else {
            response.getWriter().write("<script>alert('更新失败');location.href='/class_update/"+classes.getId()+"';</script>");

        }
    }

    @RequestMapping("/findMajor")
    @ResponseBody
    public List<Major> findMajor(){
        return classesService.findMajor();
    }



}
